package com.ywl.designpattern.singleton.type6;

/**
 * @author yuwl
 * @description 单例设计模式-懒汉式（静态内部类实现，线程安全，高效可用，推荐）
 * @since 2024-02-29 10:23
 */
public class Singleton {

    private Singleton singleton;

    private Singleton() {}

    /**
     * 静态内部类
     */
    public static class SingletonInstance {
        private static final Singleton SINGLETON = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonInstance.SINGLETON;
    }

    public static void main(String[] args) {
        Runnable runnable = () -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Singleton instance = Singleton.getInstance();
            System.out.println(Thread.currentThread().getName() + ", instance = " + instance);
            System.out.println(Thread.currentThread().getName() + ", instance.hashCode() = " + instance.hashCode());
        };

        for (int i = 0; i < 10; i++) {
            new Thread(runnable).start();
        }
    }
}
